import model.User;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import java.sql.Connection;
import java.util.List;

public class DBUtils实现CRUD操作 {


    @Test
    public void QueryRunner_update(){
        QueryRunner runner = new QueryRunner();
        Connection connection = null;
        try {
            connection = 连接池.getConnection();

            String sql = "insert into user(name,birthday)values(?,?)";
            int count = runner.update(connection, sql, "何成飞", "1992-09-08");

            System.out.println("添加了" + count + "条记录");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DbUtils.closeQuietly(connection);
        }
    }

    @Test
    public void QueryRunner_delete(){
        QueryRunner runner = new QueryRunner();
        Connection connection = null;
        try {
            connection = 连接池.getConnection();

            String sql = "delete from user where id > ?";
            int count = runner.update(connection, sql, 5);

            System.out.println("删除了" + count + "条记录");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DbUtils.closeQuietly(connection);
        }
    }


    @Test
    public void ResultSetHandler_BeanHandler(){
        QueryRunner runner = new QueryRunner();
        Connection connection = null;
        try {
            connection = 连接池.getConnection();

            String sql = "select id, name, password from user where id = ?";
            BeanHandler<User> userBeanHandler = new BeanHandler<>(User.class);
            User user = runner.query(connection, sql, userBeanHandler, 1);

            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DbUtils.closeQuietly(connection);
        }
    }

    @Test
    public void ResultSetHandler_BeanListHandler(){
        QueryRunner runner = new QueryRunner();
        Connection connection = null;
        try {
            connection = 连接池.getConnection();

            String sql = "select id, name, password from user";
            BeanListHandler<User> userBeanListHandler = new BeanListHandler<>(User.class);
            List<User> users = runner.query(connection, sql, userBeanListHandler);

            System.out.println(users);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DbUtils.closeQuietly(connection);
        }
    }




}
